package com.net.xpay.stable.job;

import com.net.common.concurrent.ThreadUtil;
import com.net.xpay.common.enums.config.CommonSysConfigKey;
import com.net.xpay.common.helper.CommonSysConfigHelper;
import com.net.xpay.common.helper.NoticeHelper;
import com.net.xpay.core.enums.SafePayOrderStatus;
import com.net.xpay.core.manager.safePay.SafePayOrderManager;
import com.net.xpay.core.model.SafePayOrderSearchModel;
import com.net.xpay.core.service.safePay.SafePayService;
import com.net.shard.ShardUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
public class SafePayOrderUpdateJob implements Runnable {

    private long shardId;

    private SafePayOrderManager safePayOrderManager;

    private SafePayService safePayService;

    private CommonSysConfigHelper commonSysConfigHelper;

    private NoticeHelper noticeHelper;

    public SafePayOrderUpdateJob(Long shardId, SafePayOrderManager safePayOrderManager,
                                 SafePayService safePayService, CommonSysConfigHelper commonSysConfigHelper, NoticeHelper noticeHelper) {
        this.shardId = shardId;
        this.safePayOrderManager = safePayOrderManager;
        this.safePayService = safePayService;
        this.commonSysConfigHelper = commonSysConfigHelper;
        this.noticeHelper = noticeHelper;
    }

    @Override
    public void run() {
        try {
            ShardUtil.setShardContext(shardId);
            while (true) {
                try {
                    doUpdateSafePayOrder();
                } catch (Throwable e) {
                    log.error("doUpdateSafePayOrder", e);
                }
                ThreadUtil.safeSleep(1000, "");
            }
        } finally {
            ShardUtil.cleanShardContext();
        }
    }

    private void doUpdateSafePayOrder() {
        Long delayTime = commonSysConfigHelper.getLong(CommonSysConfigKey.QUERY_SAFE_PAY_ORDER_DELAY_TIME);
        delayTime = delayTime == null ? 10L : delayTime;
        SafePayOrderSearchModel searchModel = new SafePayOrderSearchModel();
        searchModel.setStatus(SafePayOrderStatus.DEALING);//处理中的
        searchModel.setMinStartTime(LocalDateTime.now().minusDays(1L));
        searchModel.setMaxStartTime(LocalDateTime.now().minusSeconds(delayTime));

        List<Long> ids = safePayOrderManager.listIds(searchModel);
        if (CollectionUtils.isEmpty(ids)) {
            return;
        }

        noticeHelper.sendSystemMonitorNotice("【警告】安全付单笔到银行卡 超过" + delayTime + "秒未收到消息推送，将用接口查询订单接口|笔数：" + ids.size(), "text");
        for (Long id : ids) {
            try {
                safePayService.updateDealingSafePayOrder(id);
            } catch (Exception e) {
                log.error("doUpdateSafePayOrder error|id={}", id, e);
            }
        }
    }


}
